//
//  EMNetConfig.m
//  EasyMoney
//
//  Created by zh on 2019/12/30.
//  Copyright © 2019 zh. All rights reserved.
//

#import "EMNetConfig.h"
#import <OpenUDID.h>
#import "EMSecurityDBModel.h"
#import <AdSupport/AdSupport.h>
#import "WDPDeviceInfoManager.h"
#import <AFNetworking.h>

#define ACCESS_TOKEN @"AccessToken"
#define REFRESH_TOKEN @"RefreshToken"
#define DEVICE_ID @"DeviceID"

@interface EMNetConfig ()

@property (nonatomic, copy, nullable) NSString *at;
@property (nonatomic, copy, nullable) NSString *rt;

@end

@implementation EMNetConfig

static EMNetConfig *__instance = nil;

- (NSURL *)baseURL
{
    if (!_baseURL)
    {
        _baseURL = [NSURL URLWithString:@"http://47.92.64.95/genloan-trade/"];
    }
    return _baseURL;
}

+ (instancetype)sharedConfig
{
    if (!__instance) {
        @synchronized(self){
            if (!__instance) {
                __instance = [[EMNetConfig alloc] init];
                [__instance initParam];
            }
        }

    }
    return __instance;
}

- (void)initParam
{
    self.at = nil;
}

- (void)clearToken
{
    [EMSecurityDBModel deleteWithKey:ACCESS_TOKEN];
    self.at = nil;
    [self refreshCookieWithToken:@"0"];
    [[NSNotificationCenter defaultCenter] postNotificationName:EMAccessTokenChangeNofitication object:nil];
}

- (NSString *)getToken
{
    if (self.at == nil) {
        self.at = (NSString *)[EMSecurityDBModel objectFromKey:ACCESS_TOKEN];
        [self refreshCookieWithToken:self.at];
    }
    
    return self.at;
}

- (void)setToken:(NSString *)token
{
    if (nil == token) {
        return;
    }
    self.at = token;
    [EMSecurityDBModel storeWithKey:ACCESS_TOKEN value:self.at];
    //塞cookies
    [self refreshCookieWithToken:token];
    [[NSNotificationCenter defaultCenter] postNotificationName:EMAccessTokenChangeNofitication object:nil];
}

- (NSString *)getRefreshToken
{
    if (SAFE_STRING(self.rt).length == 0) {
        self.rt = (NSString *)[EMSecurityDBModel objectFromKey:REFRESH_TOKEN];
    }
    
    return self.rt;
}

- (void)setRefreshToken:(NSString *)refreshToken
{
    if (SAFE_STRING(refreshToken).length == 0) {
        return;
    }
    if ([SAFE_STRING(refreshToken) isEqualToString:self.rt]) {
        return;
    }
    self.rt = SAFE_STRING(refreshToken);
    [EMSecurityDBModel storeWithKey:REFRESH_TOKEN value:self.rt];
}

-(void)refreshCookieWithToken:(NSString *)token
{
    if (SAFE_STRING(token).length <= 0) {
        return;
    }
    NSString* cookie = [[NSString alloc] initWithFormat:@"accessToken=%@;path=/;domain=%@;httponly", token, self.baseURL.host];
    NSArray *headeringCookie = [NSHTTPCookie
                                cookiesWithResponseHeaderFields:
                                @{
                                  @"Set-Cookie":cookie,
                                  }
                                forURL:self.baseURL];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:headeringCookie forURL:self.baseURL mainDocumentURL:nil];
}

- (NSString *)getOpenUUID
{
    NSString *currentOpenUUID = (NSString *)[EMSecurityDBModel objectFromKey:DEVICE_ID];
    if (currentOpenUUID.length <= 0)
    {
        currentOpenUUID = [OpenUDID value];
        [EMSecurityDBModel storeWithKey:DEVICE_ID value:currentOpenUUID];
    }
    return currentOpenUUID;
}

- (NSString*)getIdfa
{
    static NSString *adid = nil;
    
    if (adid == nil) {
        adid = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    }
    
    if (adid) {
        NSString* ss = [[adid stringByReplacingOccurrencesOfString:@"-" withString:@""] stringByReplacingOccurrencesOfString:@"0" withString:@""];
        
        BOOL result = ss.length>0 ? YES:NO;
        
        if (result == NO) {
            adid = nil;
        }
    }
    
    return adid;
}

- (NSString*)agentString
{
    NSString *deviceName;
    NSString *OSName;
    NSString *OSVersion;
    UIDevice *device = [UIDevice currentDevice];
    deviceName = [device localizedModel];
    OSName = [device systemName];
    OSVersion = [device systemVersion];
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    NSString *userVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString* uuid = [NSString stringWithFormat:@"%@", [NSString deviceUUID]];
    NSString* bundleId = [[NSBundle mainBundle]bundleIdentifier];
    NSString* deviceInfo = [NSString stringWithFormat:@"%@", [WDPDeviceInfoManager deviceHardInfo]];
    NSString* networkType = nil;
    
    NSString* rootMsg = @"normal";
    if ([UIDevice currentDevice].isJailbroken == YES) {
        rootMsg = @"rooted";
    }
    
    switch ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus) {
        case AFNetworkReachabilityStatusReachableViaWiFi:
            networkType =  @"wifi";
            break;
            
        case AFNetworkReachabilityStatusReachableViaWWAN:
            networkType = @"wwan";
            break;
            
            
        default:
            networkType = @"unknow";
            break;
    }
    
    NSString *adid = [self getIdfa];
    NSString* str = nil;
    
    if (adid == nil) {
        str = [[NSString alloc]initWithFormat:@"EM/1.0(%@;%@(%@);%@;%@;%@;%@;%@;%@)", bundleId, userVersion, version, OSName,uuid, OSVersion, deviceInfo, networkType, rootMsg];
    }
    else
    {
        str = [[NSString alloc]initWithFormat:@"EM/1.0(%@;%@(%@);%@;%@(%@);%@;%@;%@;%@)", bundleId, userVersion, version, OSName,uuid, adid, OSVersion, deviceInfo, networkType, rootMsg];
    }
    return str;
}

@end
